package com.example.maoyanmovie.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.maoyanmovie.databinding.ItemMovieBinding;
import com.example.maoyanmovie.model.Movie;
import com.example.maoyanmovie.ui.activity.MovieDetailActivity;
import com.example.maoyanmovie.utils.Constants;
import java.util.ArrayList;
import java.util.List;

public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder> {

    private Context context;
    private List<Movie> movieList = new ArrayList<>();

    public MovieAdapter(Context context) {
        this.context = context;
    }

    public void setMovieList(List<Movie> movieList) {
        this.movieList = movieList;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemMovieBinding binding = ItemMovieBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
        return new ViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Movie movie = movieList.get(position);
        holder.bind(movie);
    }

    @Override
    public int getItemCount() {
        return movieList.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        ItemMovieBinding binding;

        ViewHolder(ItemMovieBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(Movie movie) {
            binding.tvName.setText(movie.getName());
            binding.tvStar.setText("主演：" + movie.getStar());
            binding.tvShowInfo.setText(movie.getShowInfo());

            if (movie.getScore() > 0) {
                binding.tvScore.setVisibility(View.VISIBLE);
                binding.tvScore.setText(String.valueOf(movie.getScore()));
            } else {
                binding.tvScore.setVisibility(View.GONE);
            }

            Glide.with(context)
                    .load(movie.getImageUrl())
                    .into(binding.ivPoster);

            binding.getRoot().setOnClickListener(v -> {
                Intent intent = new Intent(context, MovieDetailActivity.class);
                intent.putExtra(Constants.INTENT_KEY_MOVIE, movie);
                context.startActivity(intent);
            });

            binding.btnBuy.setOnClickListener(v -> {
                Intent intent = new Intent(context, MovieDetailActivity.class);
                intent.putExtra(Constants.INTENT_KEY_MOVIE, movie);
                context.startActivity(intent);
            });
        }
    }
}
